<template>
    <panel-head :route="route" />
    <div class="btn">
        <el-button :icon="Plus" type="primary" @click="open" size="small">新增</el-button>
        <el-popconfirm
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="是否确认删除？"
            confirm-button-text="是"
            cancel-button-text="否"
            @confirm="handleDelete"
        >
            <template #reference>
                <el-button type="danger" :icon="Delete" size="small">删除</el-button>
            </template>
        </el-popconfirm>
    </div>
    <el-dialog
        v-model="dialogFormVisible"
        :before-close="beforeClose"
        title="陪护师添加"
        width="500px"
    >
        <el-form
            ref="formRef"
            :rules="rules"
            :model="formData"
            label-width="100px"
            label-position="left"
        >
            <el-form-item v-show="false" prop="id">
                <el-input v-model="formData.id" />
            </el-form-item>
            <el-form-item label="昵称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入昵称" />
            </el-form-item>
            <el-form-item label="头像" prop="avatar">
                <el-button v-if="!formData.avatar" type="primary" @click="openImg">上传头像</el-button>
                <el-image
                    v-else
                    style="width: 100px; height: 100px;"
                    :src="formData.avatar"
                />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-select v-model="formData.sex" placeholder="请选择性别">
                    <el-option label="男" value="1"></el-option>
                    <el-option label="女" value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
                <el-input-number v-model="formData.age" :min="13" :max="30" />
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="formData.mobile" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="是否生效" prop="active">
                <el-radio-group v-model="formData.active">
                    <el-radio :value="1" size="large">生效</el-radio>
                    <el-radio :value="0" size="large">失效</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 点击上传头像打开头像弹框 -->
    <el-dialog
        v-model="dialogImgVisible"
        :before-close="beforeCloseImg"
        title="选择头像"
        width="680px"
    >
        <div class="image-list">
            <div class="img-box" v-for="(item, index) in avatarList" :key="item.name" @click="selectIndex = index">
                <!-- 选中头像 -->
                <div v-if="selectIndex === index" class="select">
                    <el-icon style="color: #fff;"><Check /></el-icon>
                </div>
                <el-image :src="item.url" style="width: 148px; height: 148px;" />
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogImgVisible = false">取消</el-button>
                <el-button type="primary" @click="submitImg()">确定</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 陪护师列表 -->
    <el-table :data="tableData.list" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="id" />
        <el-table-column prop="name" label="昵称" />
        <el-table-column prop="avatar" label="头像">
            <template #default="scope">
                <el-image :src="scope.row.avatar" style="width: 50px; height: 50px;"></el-image>
            </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别">
            <template #default="scope">
                {{ scope.row.sex === '1' ? '男' : '女' }}
            </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" />
        <el-table-column prop="active" label="状态">
            <template #default="scope">
                <el-tag :type="scope.row.active ? 'success' : 'danger'">{{ scope.row.active ? '正常' : '失效' }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间">
            <template #default="scope">
                <div class="flex-box">
                    <el-icon><Clock /></el-icon>
                    <span style="margin-left: 10px;">{{ scope.row.create_time }}</span>
                </div>
            </template>
        </el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <el-button size="small" type="primary" @click="open(scope.row)">编辑</el-button>
            </template>
        </el-table-column>
    </el-table>
    <div class="pagination-info">
        <el-pagination
            v-model:current-page="pagination.pageNum"
            :page-size="pagination.pageSize"
            :background="false"
            size="small"
            layout="total, prev, pager, next"
            :total="tableData.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { Plus, InfoFilled, Delete } from '@element-plus/icons-vue'
import { getPhotoList, createCaregiver, getCaregiverList, deleteCaregiver } from '@/api/'
import dayjs from 'dayjs'
import { useRoute } from 'vue-router'

const route = useRoute()
const avatarList = ref([])
const selectIndex = ref(0)
const dialogFormVisible = ref(false)
const dialogImgVisible = ref(false)
const formRef = ref()
const formData = reactive({
    id: '',
    mobile: '',
    active: 1,
    age: 28,
    avatar: '',
    name: '',
    sex: ''
})
// 陪护师数据
const tableData = reactive({
    list: [],
    total: 0
})
const pagination = reactive({
    pageNum: 1,
    pageSize: 10
})
const getTableList = () => {
    getCaregiverList(pagination).then(({ data }) => {
        const { list, total } = data.data
        list.forEach(item => {
            item.create_time = dayjs(item.create_time).format('YYYY-MM-DD')
        })
        tableData.list = list
        tableData.total = total
    })
}

// 获取头像列表，将后端接口返回回来的数据赋值给avatarList
onMounted(() => {
    getPhotoList().then(({ data }) => [
        avatarList.value = data.data
    ])
    getTableList()
})

// 规则校验
const rules = reactive({
    name: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
    avatar: [{ required: true, message: '请选择头像' }],
    sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
    mobile: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确手机号', trigger: 'blur'}
    ]
})

// 关闭弹窗
const beforeClose = () => {
    dialogFormVisible.value = false
    formRef.value.resetFields()
}
const beforeCloseImg = () => {
    dialogImgVisible.value = false
}
// 打开弹窗
const open = (rowData = {}) => {
    dialogFormVisible.value = true
    nextTick(() => {
        if (rowData) {
            Object.assign(formData, rowData)
        }
    })
}
// 提交表单
const submitForm = async (formEl) => {
    // 如果没有获取到表单实例对象，直接返回
    if (!formEl) return
    // 如果获取到表单实例对象，调用表单校验方法手动校验需要校验的表单项
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 提交表单，创建陪护师
            createCaregiver(formData).then(({ data }) => {
                console.log(data)
                if (data.code === 10000) {
                    ElMessage.success('成功')
                    beforeClose()
                    getTableList()
                } else {
                    ElMessage.error(data.message)
                }
            })
        } else {
            console.log('错误提交')
        }
    })
}

// 打开头像弹窗
const openImg = () => {
    dialogImgVisible.value = true
}
// 关闭头像选择弹框
const submitImg = () => {
    dialogImgVisible.value = false
    formData.avatar = avatarList.value[selectIndex.value].url
}

// 分页相关
const handleSizeChange = (val) => {
    pagination.pageSize = val
    getTableList()
}
const handleCurrentChange = (val) => {
    pagination.pageNum = val
    getTableList()
}
const selectDelete = ref([])
// 处理勾选哪几项（参数为你勾选的项）
const handleSelectionChange = (val) => {
    selectDelete.value = val.map(item => ({ id: item.id }))
}
// 处理删除列表项
const handleDelete = () => {
    if (selectDelete.value.length === 0) {
        ElMessage.warning('请先选择要删除项！')
    } else {
        deleteCaregiver({ id: selectDelete.value}).then(({ data }) => {
            if (data.code === 10000) {
                ElMessage.success('删除成功！')
                getTableList()
            } else {
                ElMessage.error(data.message)
            }
        })
    }
}
</script>

<style lang="less" scoped>
.btn {
    padding: 10px 0 10px 10px;
    background-color: #fff;
}
.image-list {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .img-box {
    position: relative;
    .select {
      position: absolute;
      left: 0px;
      top: 0px;
      width: 24px;
      height: 24px;
      background-color: #67c23a;
      z-index: 999;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .el-image {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
</style>